﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using FastReflectionLib;
using Newtonsoft.Json;
using System.Data;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.QY.Entities;
using SZHL.Data;
using SZHL.UI.AppCode;

namespace SZHL.UI.API
{
    public class RCTXManage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            MethodInfo methodInfo = typeof(RCTXManage).GetMethod(msg.Action.ToUpper());
            RCTXManage model = new RCTXManage();
            methodInfo.FastInvoke(model, new object[] { context, msg, P1, P2, UserInfo });
        }

        /// <summary>
        /// 添加请假数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="strParamData"></param>
        public void ADDRCTX(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                ZH_RCTX rctx = JsonConvert.DeserializeObject<ZH_RCTX>(P1);
                if (rctx.RWTitle.Trim() == "")
                {
                    msg.ErrorMsg = "任务内容不能为空";
                    return;
                }
                if (rctx.RWFZR.Trim() == "")
                {
                    msg.ErrorMsg = "请选择负责人";
                    return;
                }
                if (rctx.ID == 0)
                {
                    rctx.CRDate = DateTime.Now;
                    rctx.CRUser = UserInfo.User.UserName;
                    rctx.CRUserName = UserInfo.User.UserRealName;
                    new ZH_RCTXB().Insert(rctx);
                    //发送消息
                    string content = UserInfo.User.UserRealName + "发起了任务";
                    if (!string.IsNullOrEmpty(rctx.RWFZR))
                    {
                        new JH_Auth_User_CenterB().SendMsg(UserInfo, "rctx", "任务待办", content, rctx.ID, rctx.RWFZR);
                    }
                    if (!string.IsNullOrEmpty(rctx.RWCYR))
                    {
                        new JH_Auth_User_CenterB().SendMsg(UserInfo, "rctx", "任务待办", content, rctx.ID, rctx.RWCYR);
                    }
                }
                else
                {
                    new ZH_RCTXB().Update(rctx);
                }
                msg.Result = rctx;

            }
            catch (Exception)
            {

                msg.ErrorMsg = "添加待办失败";
            }
        }
        /// <summary>
        /// 查看任务代办的详细
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETRCTXMODEL(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strFormID = P1;
            ZH_RCTX Model = new ZH_RCTXB().GetEntity(d => d.ID.ToString() == strFormID);
            msg.Result = Model;
            msg.Result1 = new JH_Auth_TLB().GetTL("RCTX", Model.ID.ToString());
            msg.Result2 = new ZH_RCTXB().GetEntities(d => d.TopID.ToString() == strFormID);
            msg.Result3 = new ZH_RCTX_STATUSB().GetEntities(d => d.rctxId.ToString() == P1 && d.Status == 1);
            string sts = "0";
            if (!string.IsNullOrEmpty(Model.RWFZR))
            {
                if (Model.RWFZR.IndexOf(UserInfo.User.UserName) > 0)
                {
                    sts = "1";
                }
            }
            if (!string.IsNullOrEmpty(Model.RWCYR))
            {
                if (Model.RWCYR.IndexOf(UserInfo.User.UserName) > 0)
                {
                    sts = "1";
                }
            }
            if (sts == "1")
            {
                var stus = new ZH_RCTX_STATUSB().GetEntity(d => d.rctxId.ToString() == P1 && d.rwUser == UserInfo.User.UserName);
                if (stus != null)
                {
                    sts = "0";
                }
            }
            msg.Result4 = sts;
        }
        public void GETRCTXDATA(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string userName = UserInfo.User.UserName;
            string strWhere = " Where 1=1 ";
            if (P1 != "")
            {
                strWhere += string.Format(" And RWStatus={0}", P1);
            }
            if (P2 != "")
            {
                userName = context.Request["QUSER"] ?? userName;
                if (userName.Split(',').Length > 1)
                {
                    userName = UserInfo.User.UserName;
                }
                switch (P2)
                {
                    case "0":
                        strWhere += string.Format(" And (CRUser='{0}' or  ','+RWFZR+','  like '%,{0},%'  or ','+RWCYR+','  like '%,{0},%' )", userName);
                        break;
                    case "1":
                        strWhere += string.Format(" And CRUser='{0}'", UserInfo.User.UserName);
                        break;
                    case "2":
                        strWhere += string.Format(" And (','+RWFZR+','  like '%," + userName + ",%' )");
                        break;
                    case "3":
                        strWhere += string.Format(" And (','+RWCYR+','  like '%," + userName + ",%' )");
                        break;
                }
            }
            string strContent = context.Request["Content"] ?? "";
            if (strContent != "")
            {
                strWhere += string.Format(" And ( RWTitle like '%{0}%' )", strContent);
            }
            DataTable dtList = new DataTable();
            dtList = new ZH_RCTXB().GetDTByCommand(" select *  FROM ZH_RCTX " + strWhere + " ORDER BY LeiBie DESC,CRDate DESC ");
            dtList.Columns.Add("PLList", Type.GetType("System.Object"));
            for (int i = 0; i < dtList.Rows.Count; i++)
            {
                dtList.Rows[i]["PLList"] = new JH_Auth_TLB().GetTL("RCTX", dtList.Rows[i]["ID"].ToString());
            }
            msg.Result = dtList;
        }
        public void GETRCTXDATA_PAGE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string userName = UserInfo.User.UserName;
            string strWhere = "1=1";// "  isnull(TopID,0)=0";
            if (P1 != "")
            {
                strWhere += string.Format(" And RWStatus={0}", P1);
                if (P1 == "0")
                {
                    strWhere += " and (status.Status!=1 or status.Status is NULL)   ";
                }
            }
            userName = context.Request["QUSER"] ?? userName;
            if (userName.Split(',').Length > 1 || userName == "")
            {
                msg.ErrorMsg = "请选择具体的人员查看任务列表";
                return;
            }
            if (P2 != "")
            {

                switch (P2)
                {
                    case "0":
                        strWhere += string.Format(" And (CRUser='{0}' or  ','+RWFZR+','  like '%,{0},%'  or ','+RWCYR+','  like '%,{0},%' )", userName);
                        break;
                    case "1":
                        strWhere += string.Format(" And CRUser='{0}'", userName);
                        break;
                    case "2":
                        strWhere += string.Format(" And (','+RWFZR+','  like '%," + userName + ",%' )");
                        break;
                    case "3":
                        strWhere += string.Format(" And (','+RWCYR+','  like '%," + userName + ",%' )");
                        break;
                    case "4":
                        strWhere += string.Format(" And (','+RWFZR+','  like '%,{0},%'  or ','+RWCYR+','  like '%,{0},%' ) and CRUser!='{0}' ", userName);
                        break;
                }
            }
            string strContent = context.Request["Content"] ?? "";
            if (strContent != "")
            {
                strWhere += string.Format(" And ( RWTitle like '%{0}%' )", strContent);
            }
            DataTable dtList = new DataTable();
            int page = 0;
            int.TryParse(context.Request.QueryString["p"] ?? "1", out page);
            page = page == 0 ? 1 : page;
            int total = 0;
            dtList = new ZH_XTGGB().GetDataPager(@"ZH_RCTX  rctx left join ZH_RCTX_STATUS  status on rctx.ID=status.rctxId 
                                                   and (','+rctx.RWCYR+','  like '%,'+status.rwUser+',%' or ','+rctx.RWFZR+','  like '%,'+status.rwUser+',%' ) and status.rwUser='" + UserInfo.User.UserName + "' ", " rctx.*,status.Status ", 8, page, "RWStatus,rctx.CRDate desc", strWhere, ref total);

            string Ids = "";
            string fileIDs = "";
            foreach (DataRow row in dtList.Rows)
            {
                Ids += row["ID"].ToString() + ",";
                if (!string.IsNullOrEmpty(row["Files"].ToString()))
                {
                    fileIDs += row["Files"].ToString() + ",";
                }
            }
            Ids = Ids.TrimEnd(',');
            fileIDs = fileIDs.TrimEnd(',');
            if (Ids != "")
            {
                DataTable dtPL = new JH_Auth_TLB().GetDTByCommand(string.Format("SELECT ID,MSGTLYID,MSGType,MSGContent,CRDate,CRUser,CRUserName  FROM JH_Auth_TL WHERE MSGType='RCTX' AND  MSGTLYID in ({0})", Ids));
                List<FT_File> FileList = new FT_FileB().GetEntities(d => fileIDs.Split(',').Contains(d.ID.ToString())).ToList();
                //任务的参与人及负责人的状态
                List<ZH_RCTX_STATUS> rcStatus = new ZH_RCTX_STATUSB().GetEntities(d => Ids.Split(',').Contains(d.rctxId.Value.ToString())).ToList();
                dtList.Columns.Add("PLList", Type.GetType("System.Object"));
                dtList.Columns.Add("FileList", Type.GetType("System.Object"));
                dtList.Columns.Add("RCTXStatus", Type.GetType("System.Object"));
                foreach (DataRow row in dtList.Rows)
                {
                    row["PLList"] = dtPL.FilterTable("MSGTLYID=" + row["ID"]);
                    if (FileList.Count > 0)
                    {

                        string[] fileIds = row["Files"].ToString().Split(',');
                        row["FileList"] = FileList.Where(d => fileIds.Contains(d.ID.ToString())).ToList();
                    }
                    else
                    {
                        row["FileList"] = "";
                    }
                    if (rcStatus.Count > 0)
                    {
                        row["RCTXStatus"] = rcStatus.Where(d => d.rctxId.ToString() == row["ID"].ToString()).ToList();
                    }
                }
            }

            dtList.Columns.Add("ZRWCount", Type.GetType("System.String"));
            dtList.Columns.Add("ISGB", Type.GetType("System.String"));
            for (int i = 0; i < dtList.Rows.Count; i++)
            {
                var rctxs = new ZH_RCTXB().GetEntities(p => p.TopID.ToString() == dtList.Rows[i]["ID"].ToString() && p.RWStatus == "0");
                dtList.Rows[i]["ZRWCount"] = rctxs.Count();
                //任务状态为进行中，并且创建人是当前登录人,并且子任务中没有进行中的任务,可以关闭此任务 && rctxs.Count() == 0
                if (dtList.Rows[i]["RWStatus"].ToString() == "0" && dtList.Rows[i]["CRUser"].ToString() == UserInfo.User.UserName)
                {
                    dtList.Rows[i]["ISGB"] = "Y";
                }

            }

            msg.Result = dtList;
            msg.Result1 = total;
        }
        public void GETZRWDATA(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string userName = UserInfo.User.UserName;
            string strWhere = " Where 1=1 ";
            if (P1 != "")
            {
                strWhere += string.Format(" And TopID={0}", P1);
            }

            DataTable dtList = new DataTable();
            dtList = new ZH_RCTXB().GetDTByCommand(" select *  FROM ZH_RCTX " + strWhere + " ORDER BY LeiBie DESC,CRDate DESC ");
            dtList.Columns.Add("PLList", Type.GetType("System.Object"));
            for (int i = 0; i < dtList.Rows.Count; i++)
            {
                dtList.Rows[i]["PLList"] = new JH_Auth_TLB().GetTL("RCTX", dtList.Rows[i]["ID"].ToString());
            }
            dtList.Columns.Add("ZRWCount", Type.GetType("System.String"));
            dtList.Columns.Add("ISGB", Type.GetType("System.String"));
            for (int i = 0; i < dtList.Rows.Count; i++)
            {
                var rctxs = new ZH_RCTXB().GetEntities(p => p.TopID.ToString() == dtList.Rows[i]["ID"].ToString());
                dtList.Rows[i]["ZRWCount"] = rctxs.Count();

                if (dtList.Rows[i]["RWStatus"].ToString() == "0" && dtList.Rows[i]["RWFZR"].ToString() == UserInfo.User.UserName)
                {
                    dtList.Rows[i]["ISGB"] = "Y";
                }
                if (dtList.Rows[i]["ISGB"] != null && dtList.Rows[i]["ISGB"].ToString() == "Y")
                {
                    foreach (var r in rctxs)
                    {
                        if (r.RWStatus == "0")
                        {
                            dtList.Rows[i]["ISGB"] = "";
                        }
                    }
                }
            }
            msg.Result = dtList;
        }
        public void DELRWDB(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            new ZH_RCTXB().Delete(D => D.ID.ToString() == P1);
        }

        public void COMPLETERCTX(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            //如果提醒状态的评论带结束标志，更新待办的状态
            new ZH_RCTXB().ExsSql("UPDATE [dbo].[ZH_RCTX] SET RWStatus='" + P2 + "' WHERE ID='" + P1 + "'");//
            msg.Result = "";
        }
        /// <summary>
        /// 完成个人任务
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void COMGRRCTX(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            ZH_RCTX_STATUS rcStatus = new ZH_RCTX_STATUSB().GetEntity(d => d.rctxId.ToString() == P1 && d.rwUser == UserInfo.User.UserName);
            if (rcStatus != null)
            {
                rcStatus.Status = int.Parse(P2);
                new ZH_RCTX_STATUSB().Update(rcStatus);
            }
            else
            {
                rcStatus = new ZH_RCTX_STATUS();
                rcStatus.CRDate = DateTime.Now;
                rcStatus.rctxId = int.Parse(P1);
                rcStatus.rwUser = UserInfo.User.UserName;
                rcStatus.Status = int.Parse(P2);
                rcStatus.rwUserName = UserInfo.User.UserRealName;
                new ZH_RCTX_STATUSB().Insert(rcStatus);
            }
        }
        public void GETRCTXSTATUS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new ZH_RCTX_STATUSB().GetEntities(d => d.rctxId.ToString() == P1);
        }

    }


}
